package com.example.whm;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.app.ProgressDialog;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.CheckBox;
import org.holoeverywhere.widget.TextView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.model.Box;
import com.example.whm.model.EntityBuy;
import com.example.whm.model.Item;
import com.example.whm.model.Subscribe;
import com.example.whm.model.SubscribeItem;

public class ThreeFragmentItem extends Fragment  implements OnItemClickListener,OnClickListener{

	private AQuery aq;
	private AQuery aq2;
	
	private String id;
	boolean tag=false;
	List<SubscribeItem> data;
	List<Item> list;
    String topic_cur;
	int pos_cur;
	Bundle bun;
	int index;
	String result;
	Subscribe sub;
	CheckBox checkb;
	adapter adap;
	ProgressDialog dialog;
	TextView sub_price_t;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        
    	View view = inflater.inflate(R.layout.three_layout_fragment, container, false);        	
		System.out.println("onCreateView");
		//System.out.println("getArguments()==null   ->"+(getArguments()==null));
		//System.out.println("savedInstanceState==null   ->"+(savedInstanceState==null));
    	if (getArguments()!=null) {
    		bun=getArguments();
    		id=getArguments().getString("id");
    		index=getArguments().getInt("pos");
    		result=getArguments().getString("result");
		//	System.out.println("getArguments() topic=="+getArguments().getString("topic"));;
		//	System.out.println("getArguments() pos=="+getArguments().getInt("pos"));;
		}
    	aq = new AQuery(getActivity(), view);
    	aq2 = new AQuery(getActivity());
    	aq.find(R.id.three_layout_fragment_progress).visible();
    	//aq.id(R.id.three_layout_fragment_listview).itemClicked(this);
    	//Log.i("TwoFragmentItem", "tonCreateView---------------i="+i);
    	//Log.i("TwoFragmentItem", "---------------onCreateView");
    	//Log.i("TwoFragmentItem", "---------------onCreateView savedInstanceState="+(savedInstanceState==null));
    	//Log.i("TwoFragmentItem", "---------------onCreateView getArguments()="+(getArguments().getInt("pos")));
		return view;
		
    }
    
    @Override
	public void onActivityCreated(Bundle savedInstanceState){

    	//System.out.println("onActivityCreated");
    	super.onActivityCreated(savedInstanceState);
    	Bundle b=new Bundle();
    	
    	
    	//	getLoaderManager().initLoader(0, bun, this);
    	   if (index==0) {
    		   init();    		   
    		 //bun.putString("url", "http://219.239.236.77/statuses/puzzles"); 
    		   //getLoaderManager().initLoader(0, bun, this);
		}
    		
    	
    	
    }

    
    
    
    
    
    
    
    
    
    
    
    public void init(){
    	
    	
    	//Log.i("TwoFragmentItem", "---------------init");
    	if (aq==null||tag) return;
    	tag=true;
    	
    	String url = "http://"+Whm_app.api_url+":9000/api/subcribe/"+id;
    	//String url = "http://219.239.236.77/statuses/puzzles";
    	/*if (result!=null) {
			ui(result);
			System.out.println("result!=null========");
		}else{
			
			aq.ajax(url, String.class, this, "parsedata");
		}*/
    	aq.ajax(url, String.class, this, "parsedata");
    	//bun.putString("url", "http://219.239.236.77/statuses/puzzles"); 
    	//getLoaderManager().initLoader(0, bun, this);
    
    }

    public void parsedata(String url, String s, AjaxStatus status){
    	System.out.println("status.getCode()==="+status.getCode());
    	if (status.getCode()==200) {
    		if(s != null){   			
        		ui(s);
        	}
		}else{
			aq.find(R.id.three_layout_fragment_progress).gone();
		}
    	
    	
    }

 public void ui(String str){
	 final String s=str;
	 new Thread( new Runnable() {
         @Override
		public void run() {
        	// String s1= JSON.parseObject(s).getString("users");
        	 String s1= JSON.parseObject(s).getString("result");
        	 String s2= JSON.parseObject(s1).getString("sub");
        	 String s3= JSON.parseObject(s1).getString("comments");
        	 final int comm_size= JSON.parseArray(s3).size();
     		//System.out.println(s2);
     		
        	  sub=JSON.parseObject(s2, Subscribe.class);
             data = sub.getSub_items();
        	// System.out.println(data.size());
                 getActivity().runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
					//	Toast.makeText(getActivity(), "list.size="+list.size(), 1000).show(); 
			     	//	Toast.makeText(getActivity(), "data.size="+data.size(), 1000).show();
						View v=getActivity().getLayoutInflater().inflate(R.layout.sud_listview_footview, null);
					   
						AQuery a=new AQuery(v);
						
						a.find(R.id.sub_listview_fra_comment).text(String.valueOf(comm_size)).clicked(ThreeFragmentItem.this);
						a.find(R.id.sub_listview_fra_tianshu).text(String.valueOf(sub.getValid_days()));
						a.find(R.id.sub_listview_fra_price).text(String.valueOf(sub.getPrice()));
						a.id(R.id.sub_listview_fra_btn_sub).clicked(ThreeFragmentItem.this);
						
						sub_price_t=(TextView) a.find(R.id.sub_listview_fra_subprice).getTextView();
						sub_price_t.setText(String.valueOf(sub.getSub_price()));
						aq.id(R.id.three_layout_fragment_listview).getListView().addFooterView(v);
					    adap=new adapter(data);
						aq.id(R.id.three_layout_fragment_listview).adapter(adap).visible();
						//aq.id(R.id.three_layout_listview).visible();
						aq.find(R.id.three_layout_fragment_progress).gone();
						
					}
				});
          }
 }).start();
 } 
	
	
	
	
	
	class adapter extends BaseAdapter{

		
		List<SubscribeItem> list;
		public adapter() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		
		
		public List<SubscribeItem> getList() {
			return list;
		}




		public void setList(List<SubscribeItem> list) {
			this.list = list;
		}




		public adapter(List<SubscribeItem> list) {
			super();
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			System.out.println("arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.three_layout_item, arg2);
			}
			
			
			SubscribeItem i = (SubscribeItem) getItem(arg0);
			ids.add(i.getId());
			ids_sub.add(i);
			
			AQuery aq = aq2.recycle(arg1);
			aq.id(R.id.three_layout_item_date).text(i.getDetail_date());
			aq.id(R.id.three_layout_item_price).text(String.valueOf(i.getPrice()));
			System.out.println("JSON.toJSONString(i.getList())--------"+JSON.toJSONString(i.getList()));
			aq.id(R.id.three_layout_item_grid).adapter(new adapter2(i.getList())).itemClicked(ThreeFragmentItem.this); 
		    checkb=(CheckBox) aq.id(R.id.three_layout_item_check).getCheckBox();
			checkb.setTag(arg0);
			checkb.setOnClickListener(ThreeFragmentItem.this);
		    return arg1;
		}
		
		
	}

	class adapter2 extends BaseAdapter{

		
		List<EntityBuy> list;
		public adapter2() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		public adapter2(List<EntityBuy> list) {
			super();
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.three_layout_grid_item, arg2);
			}
			
			EntityBuy i = (EntityBuy) getItem(arg0);
			AQuery aq = aq2.recycle(arg1);
		
			String tbUrl = i.getEntity().getPre_pic().replace("localhost", Whm_app.api_url);
		
			if(aq.shouldDelay(arg0, arg1, arg2, tbUrl)){
				aq.id(R.id.three_layout_grid_item_imagevie).clear();
			}else{
				aq.id(R.id.three_layout_grid_item_imagevie).image(tbUrl, true, true, 200, R.drawable.ic_launcher, null,0, 0);
			}
			
			return arg1;
		}
		
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		EntityBuy i=(EntityBuy) arg0.getItemAtPosition(arg2);
		 Intent inte=new Intent(getActivity(), EntityDetail.class);
		 String id=i.getEntity().getId();
		  if (inte.getExtras()!=null) {
			  inte.getExtras().putString("id",id);
		}else{
			Bundle b=new Bundle();
			b.putString("id", id);
			inte.putExtras(b);
		}
		  startActivity(inte);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.sub_listview_fra_comment:
			
			Toast.makeText(getActivity(), "onclick", 1000).show();
			
			break;
        case R.id.sub_listview_fra_btn_sub:
			
			if (ids.size()<sub.getValid_days()) {
				Toast.makeText(getActivity(), "Valid_days must be thaner of"+sub.getValid_days(), 1000).show();
			}else{
				sub();
			}
			break;
        case R.id.three_layout_item_check:
        	check_do(v);
        	break;
		default:
			break;
		}
	}

	public void show_dialog(boolean b){
	
		if (dialog==null) {
			dialog = new ProgressDialog(getSupportActivity());
		    dialog.setIndeterminate(true);
		    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		    dialog.setMessage("post");
		}
		if (b) {
			dialog.show();
		}else{
			dialog.dismiss();
		} 
	    
	}
	
	boolean is_check=true;
	List<String> ids=new ArrayList<String>();
	List<SubscribeItem> ids_sub=new ArrayList<SubscribeItem>();
	
	public void check_do(View v){
		CheckBox ch=(CheckBox)v;
		int pos=(Integer)ch.getTag();
		SubscribeItem box=adap.getList().get(pos);
		String id=box.getId();
		if (ch.isChecked()) {
			
			if (!ids.contains(id)) {
				ids.add(id);
			}
			if (!ids_sub.contains(box)) {
				ids_sub.add(box);
			}
			
		}else{
			
			ids.remove(id);
			ids_sub.remove(box);
		}
		
		int p=0;
		for(SubscribeItem i: ids_sub){
			p=p+i.getPrice();
		}
		int sub_price=Double.valueOf(Math.floor(p*0.9)).intValue();
		sub_price_t.setText(String.valueOf(sub_price));
			
	}
	
	
	public void sub(){
		if (!ids.isEmpty()) {
			Map<String, Object> params = new HashMap<String, Object>();
		    params.put("type", 3);
		    params.put("id", sub.getId());
		    params.put("coll", sub.getClass().getSimpleName());
		    String item_ids="";
		    for(String s:ids){
		    	item_ids=item_ids+s+",";
		    }
		    
		    params.put("item_ids", item_ids.substring(1, item_ids.length()-1));
		    params.put("sub_price", sub_price_t.getText().toString());
		  
		    System.out.println("sub params===="+JSON.toJSONString(params));
		    String url="http://"+Whm_app.api_url+":9000/api/buy_func";
		  AjaxCallback<String> cb = new AjaxCallback<String>();        
		  cb.url(url).type(String.class).weakHandler(ThreeFragmentItem.this, "buy_func_result");

		  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
		String cookiename=sp.getString("cookie_name",null);
		String cookievalue=sp.getString("cookie_value",null);
		if (cookiename!=null&&cookievalue!=null) {
			cb.cookie(cookiename,cookievalue);               
		}
		show_dialog(true);	
		cb.params(params);

		aq.ajax(cb);
		}else{
			Bundle b=new Bundle();
			b.putString("skip", "0");	
			Intent i=new Intent(getActivity(), Login.class);
		    i.putExtras(b);
			startActivity(i);
		}
		
	}

	public void buy_func_result(String url, String r, AjaxStatus status){
		show_dialog(false);
		 if (status.getCode()==200) {
			 if (!Whm_app.newl.contains(3)) {
				 Whm_app.newl.add(3);
			}
			 Toast.makeText(getActivity(), "subscribe ok", 1000).show();
			  
		 }else{
			 Toast.makeText(getActivity(), "parse error", 1000).show();
		 }
		
		
	}
    
    

 
}
